package com.bigstonecontainer.training.springboot.frm.server.core.service.impl;

import com.bigstonecontainer.training.springboot.frm.server.core.cache.CoreCache;
import com.bigstonecontainer.training.springboot.frm.server.core.domain.LoginUser;
import com.bigstonecontainer.training.springboot.frm.server.core.domain.Result;
import com.bigstonecontainer.training.springboot.frm.server.core.exception.FrmServerException;
import com.bigstonecontainer.training.springboot.frm.server.core.mapper.AuthMapper;
import com.bigstonecontainer.training.springboot.frm.server.core.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.UUID;

@Service
@Transactional
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper userMapper;

    @Override
    public LoginUser authenticate(String userName, String password) {
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) {
            throw new FrmServerException(Result.error("用户名和密码都不能为空"));
        }
        LoginUser user = userMapper.getUserAndRoleIdsByName(userName);
        if (user == null) {
            throw new FrmServerException(Result.error("用户名或者密码不正确"));
        }
        // 校验密码
        match(password, user.getPassword(), false);
        String token = String.format("BSC-USER-SPRINGBOOT-%s", UUID.randomUUID().toString());
        user.setToken(token);
        CoreCache.USERS.put(token, user);
        return user;
    }

    private void match(String passwordFromUI, String passwordFromDB, boolean encrypt) {
        if (encrypt) {
            // 密码需要加密后比较
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (!encoder.matches(passwordFromUI, passwordFromDB)) {
                throw new FrmServerException(Result.error("用户名或者密码不正确"));
            }
        } else {
            if (!Objects.equals(passwordFromUI, passwordFromDB)) {
                throw new FrmServerException(Result.error("用户名或者密码不正确"));
            }
        }
    }

    @Override
    public void logout(String token) {
        CoreCache.USERS.remove(token);
    }
}
